﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace Eventory_Product
{
    partial class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:/XMLFile.xml";
            if (!File.Exists(path))
            {
                using(FileStream fs = File.Create(path, 1024))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes("<kho></kho>");
                    // Add information root node
                    fs.Write(info, 0, info.Length);
                }
                Console.Write("File da duoc tao voi dia chi " + path);
                Console.ReadLine();
                Console.Clear();
            }
            main objMain = new main();
            objMain.start();
        }
    }
    class validate
    {        
        public string TenSP(string name)
        {
            int n = name.Length;
            if (n < 1 || n > 30)
                return "\tTen SP phai lon hon 0 va nho hon 30 ky tu";
            else
                return "";
        }

        public string MaSP(string code, List<sp> ListNode)
        {
            string error = "";
            int n = code.Length;
            if (n < 1 || n > 5)
                error += "\tMa SP phai lon hon 0 va nho hon 6 ky tu";
            else
                error += ""; 
            
            foreach (sp objSp in ListNode)
            {                
                if (code == objSp.id)
                {
                    error += "\tMa SP nay da ton tai, Moi nhap lai";
                    return error;
                }
            }
            return error;
        }
        public string GiaSP(Int64 price)
        {
            if (price < 1000000 || price > 9999999)
                return "\tTen SP phai lon hon 1000000 va nho hon 9999999";
            else
                return "";
        }
        public string SoLuong(long sl)
        {
            if (sl < 1 || sl > 1000)
                return "\tSo luong phai lon hon 0 va nho hon 1000";
            else
                return "";
        }
        public char question(string choose)
        {
            if (choose == "C" || choose == "c")
                return 'C';
            else
                return 'K';
        }
    }
    class sp
    {
        public string name{set; get;}
        public string soluong{set; get;}
        public string id{set; get;}
        public string dongia { set; get; }
    }
    class main
    {
        List<sp> listNode;
        string filename = "C:\\XMLFile.xml";
        validate objValidate = new validate();


        //Chuyen cac node tren file xml vao 1 list
        public void XmlToList()
        {
            if (listNode.Count != 0)
                listNode.Clear();            
            XmlDocument doc = new XmlDocument();
            doc.Load(filename);
            XmlNodeList nodeList = doc.GetElementsByTagName("sp");
            foreach (XmlNode node in nodeList)
            {
                sp objSP = new sp();
                XmlElement spElement = (XmlElement)node;
                objSP.name = spElement.GetElementsByTagName("name")[0].InnerText;
                objSP.id = spElement.GetElementsByTagName("id")[0].InnerText;
                objSP.dongia = spElement.GetElementsByTagName("DonGia")[0].InnerText;
                objSP.soluong = spElement.GetElementsByTagName("SoLuong")[0].InnerText;
                listNode.Add(objSP);
            }
        }

        //Chuyen cac node co tren list vao file xml

        public void ListToXml()
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(filename);

            XmlNode root = doc.DocumentElement;

            root.RemoveAll();

            //XmlNodeList nodeList = doc.GetElementsByTagName("sp");

            foreach (sp objSP in listNode)
            {
                XmlNode node = doc.CreateNode(XmlNodeType.Element, "sp",null);
                //node.InnerText = "this is new node";

                //create title node
                XmlNode nodeName = doc.CreateElement("name");
                //add value for it
                nodeName.InnerText = objSP.name.ToString();

                //create Url node
                XmlNode nodeID = doc.CreateElement("id");
                nodeID.InnerText = objSP.id;

                //create DonGia node
                XmlNode nodeDonGia = doc.CreateElement("DonGia");
                nodeDonGia.InnerText = objSP.dongia;

                //create SoLuong node
                XmlNode nodeSoLuong = doc.CreateElement("SoLuong");
                //add value for it
                nodeSoLuong.InnerText = objSP.soluong;

                //add to parent node
                node.AppendChild(nodeName);
                node.AppendChild(nodeID);
                node.AppendChild(nodeDonGia);
                node.AppendChild(nodeSoLuong);

                //add to elements collection
                doc.DocumentElement.AppendChild(node);
                doc.Save(filename);
            }

        }

        private int Menu()
        {
            int choose = 0;
            Console.WriteLine("\n\n========HE THONG QUAN LY HANG NHAP KHO========");
            Console.WriteLine("                     +++                      ");
            Console.WriteLine("\n\t\tChuc nang he thong");
            Console.WriteLine("\t\t1. Them moi san pham");
            Console.WriteLine("\t\t2. Sua san pham");
            Console.WriteLine("\t\t3. Xoa san pham");
            Console.WriteLine("\t\t4. Tim san pham theo MA");
            Console.WriteLine("\t\t5. Tim san pham theo TEN");
            Console.WriteLine("\t\t6. Thong ke san pham ton kho");
            Console.WriteLine("\t\t7. Thoat");
            Console.Write("\n\tMoi chon chuc nang thuc hien: ");

            try
            {
                choose = Convert.ToInt16(Console.ReadLine());
            }
            catch (Exception ex)
            {
                choose = 0;
            }

            while (choose < 1 || choose > 7)
            {
                try
                {
                    Console.Write("\n\tChuc nang khong san sang.\nMoi nhap lai: ");
                    choose = Convert.ToInt16(Console.ReadLine());
                }
                catch (Exception ex)
                {
                    choose = 0;
                }
            }
            return choose;

        }


        public void start()
        {
            listNode = new List<sp>();
            switch (Menu())
            {
                case 1:
                    ThemSP();                    
                    break;
                case 2:
                    SuaSP();
                    break;
                case 3:
                    XoaSP();
                    break;
                case 4:
                    TimMaSP();
                    break;
                case 5:
                    TimTenSP();
                    break;
                case 6:
                    ThongKeSP();
                    break;
                case 7:
                    Thoat();
                    break;
            }

        }

        //Kiem tra xem ID co ton tai tren file hay khong
        //flag = true thi tim theo ma, nguoc lai tim theo ten SP
        private bool checkID(string IdSP)
        {
            XmlToList();         
            foreach (sp objSP in listNode)
            {
                if (objSP.id == IdSP)
                    return false;
            }                       
            return true;
        }

        private void SortList()
        {
            listNode.Sort(Compare);
            ListToXml();
        }
        static public int Compare(sp x, sp y)
        {

            return x.name.CompareTo(y.name);
        }
        // Them sp vao list, sau do cap nhat lai file xml
        private void ThemSP()
        {
            validate objValidate = new validate();        
        them:
            XmlToList();
            Console.WriteLine("\n\n\t=== THEM MOI SAN PHAM ===");
        ten:
            Console.Write("\tTen SP: ");
            string ten = Console.ReadLine();
            while (objValidate.TenSP(ten) != "")
            {
                Console.WriteLine(objValidate.MaSP(ten,listNode));
                goto ten;
            }

        ma:
            Console.Write("\tMa SP: ");
            string MaSP = Console.ReadLine();
            while (objValidate.MaSP(MaSP,listNode) != "")
            {
                Console.WriteLine(objValidate.MaSP(MaSP,listNode));
                goto ma;
            }
        gia:
            Console.Write("\tGia SP : ");
            Int64 GiaSP = -1;
            try
            {
                GiaSP = Convert.ToInt64(Console.ReadLine());
            }
            catch (Exception ex)
            {
                GiaSP = -1;
            }
            while (objValidate.GiaSP(GiaSP) != "")
            {
                Console.WriteLine(objValidate.GiaSP(GiaSP));
                goto gia;
            }
        sl:
            Console.Write("\tSo Luong SP : ");            
            Int64 SoLuong = -1;
            try
            {
                SoLuong = Convert.ToInt16(Console.ReadLine());
            }
            catch (Exception ex)
            {
                SoLuong = -1;
            }
            while (objValidate.SoLuong(SoLuong) != "")
            {
                Console.WriteLine(objValidate.SoLuong(SoLuong));
                goto sl;
            }
            

            //Them moi san pham vao List và sau đó cập nhập vào File
            sp objSP = new sp();
            objSP.name = ten;
            objSP.id = MaSP;
            objSP.dongia = GiaSP.ToString();
            objSP.soluong = SoLuong.ToString();
            listNode.Add(objSP);
            listNode.Sort(delegate(sp obj1, sp obj2)
            {
                return obj1.name.CompareTo(obj2.name);
            });
            ListToXml();

            Console.Write("\nBan co muon tiep tuc them moi nua khong(C/K)");
            string choose = "";
            choose = Console.ReadLine();
            char resultChoose = objValidate.question(choose);
            if (resultChoose == 'C')
            {
                Console.Clear();
                goto them;
            }
            else
            {
                Console.Clear();
                start();
            }
        }

        private void SuaSP()
        {
        lblSuaSP:
            XmlToList();
            Console.Write("\tMoi nhap ma san pham ma ban can sua : ");
            string MaSP = Console.ReadLine();

            if (checkID(MaSP))
            {
                Console.Write("\tMaSP nay khong ton tai!\nBan co tiep tuc khong(C/K)?");
                string choose = "";
                choose = Console.ReadLine();
                char resultChoose = objValidate.question(choose);
                if (resultChoose == 'C')
                    goto lblSuaSP;
                else
                {
                    Console.Clear();
                    start();
                }
            }
            else
            {
                Console.WriteLine("\t====== THONG TIN SAN PHAM MA " + MaSP + "======");
                sp objSP = listNode.Find(x => x.id == MaSP);
                Console.WriteLine("\tMa SP: " + objSP.id);
                Console.WriteLine("\tTen SP: " + objSP.name);
                Console.WriteLine("\tGia SP: " + objSP.dongia);
                Console.WriteLine("\tSo luong SP: " + objSP.soluong);

                listNode.Remove(listNode.Find(x => x.id == MaSP));

                Console.WriteLine("\n\t====== MOI NHAP THONG TIN CAN SUA ======");

            tenSua:
                Console.Write("\tTen SP: ");
                string ten = Console.ReadLine();
                while (objValidate.TenSP(ten) != "")
                {
                    Console.Write(objValidate.TenSP(ten));
                    goto tenSua;
                }

            maSua:
                Console.Write("\tMa SP: ");
                string Masp = Console.ReadLine();
                while (objValidate.MaSP(MaSP,listNode) != "")
                {
                    Console.WriteLine(objValidate.MaSP(Masp,listNode));
                    goto maSua;
                }
            giaSua:
                Console.Write("\tGia SP : ");
                Int64 GiaSP = -1;
                try
                {
                    GiaSP = Convert.ToInt64(Console.ReadLine());
                }
                catch (Exception ex)
                {
                    GiaSP = -1;
                }
                while (objValidate.GiaSP(GiaSP) != "")
                {
                    Console.WriteLine(objValidate.GiaSP(GiaSP));
                    goto giaSua;
                }
            slSua:
                Console.Write("\tSo Luong SP : ");
                Int64 SoLuong = -1;
                try
                {
                    SoLuong = Convert.ToInt16(Console.ReadLine());
                }
                catch (Exception ex)
                {
                    SoLuong = -1;
                }
                while (objValidate.SoLuong(SoLuong) != "")
                {
                    Console.WriteLine(objValidate.SoLuong(SoLuong));
                    goto slSua;
                }
            

                //Them moi san pham vao List và sau đó cập nhập vào File
                objSP = new sp();
                objSP.name = ten;
                objSP.id = MaSP;
                objSP.dongia = GiaSP.ToString();
                objSP.soluong = SoLuong.ToString();
                listNode.Add(objSP);
                SortList();
                Console.Write("\n\th\nBan co muon tiep tuc sua SP nua khong(C/K)");
                string choose = "";
                choose = Console.ReadLine();
                char resultChoose = objValidate.question(choose);
                if (resultChoose == 'C')
                {
                    Console.Clear();
                    goto lblSuaSP;
                }
                else
                {
                    Console.Clear();
                    start();
                }
            }            
        }
       
        //Xoa 1 san pham dua vao ma san pham ma nguoi dung nhap vao
        private void XoaSP()
        {
            lblXoaSP:
            XmlToList();
            Console.Write("\tMoi nhap ma san pham ma ban muon xoa: ");
            string MaSP = Console.ReadLine();
            string choose = "";
            char resultChoose;
            if (checkID(MaSP))
            {
                Console.Write("\tMaSP nay khong ton tai!\nBan co nhap lai khong(C/K)?");                
                choose = Console.ReadLine();
                resultChoose = objValidate.question(choose);
                if (resultChoose == 'C')
                {
                    Console.Clear();
                    goto lblXoaSP;
                }
                else
                {
                    Console.Clear();
                    start();
                }
            }
            else
            {
                listNode.Remove(listNode.Find(x => x.id == MaSP));
                SortList();
            }
            Console.WriteLine("\tSAN PHAM DA XOA!");
            Console.Write("\n\tBan co muon tiep tuc them moi nua khong(C/K)");
            choose = "";
            choose = Console.ReadLine();
            resultChoose = objValidate.question(choose);
            if (resultChoose == 'C')
                goto lblXoaSP;
            else
            {
                Console.Clear();
                start();
            }
        }

        private void TimTenSP()
        {
            lblTimTenSP:
            XmlToList();
            Console.Write("Moi nhap TEN san pham ma can sua : ");
            string TenSP = Console.ReadLine();

            string choose = "";
            char resultChoose;            

            List<sp> listResult = new List<sp>();
            listResult = listNode.FindAll(x => x.name == TenSP);
            Console.WriteLine("====KET QUA====");
            Console.WriteLine("Ma SP  |     Ten SP      |    SoLuong     |     DonGia");                
            if (listResult.Count != 0)
            {
                foreach (sp objSP in listResult)
                {
                    Console.WriteLine("  {0}\t\t{1}\t\t{2}\t\t{3}", objSP.id, objSP.name, objSP.soluong, objSP.dongia);                
                }
            }

            Console.Write("\n\nBan co muon tiep tuc tim kiem nua khong(C/K)");
            choose = Console.ReadLine();
            resultChoose = objValidate.question(choose);
            if (resultChoose == 'C')
            {
                goto lblTimTenSP;
                Console.Clear();
            }
            else
            {
                Console.Clear();
                start();
            }
        }

        private void TimMaSP()
        {
        lblTimMaSP:
            XmlToList();
            Console.Write("\tMoi nhap MA san pham ma can sua : ");
            string MaSP = Console.ReadLine();

            string choose = "";
            char resultChoose;
            
            sp objSP = listNode.Find(x => x.id == MaSP);
            Console.WriteLine("\n\t====KET QUA====\n");
            Console.WriteLine("\t\tMa SP  |     Ten SP      |    SoLuong     |     DonGia");            
            if (objSP != null)
            {
                Console.WriteLine("\t\t  {0}\t\t{1}\t\t{2}\t\t{3}", objSP.id, objSP.name, objSP.soluong, objSP.dongia);                
            }
            Console.Write("\n\t\nBan co muon tiep tuc tim kiem nua khong(C/K)");
            choose = Console.ReadLine();
            resultChoose = objValidate.question(choose);
            if (resultChoose == 'C')
            {
                goto lblTimMaSP;
                Console.Clear();
            }
            else
            {
                Console.Clear();
                start();
            }
        }

        private void ThongKeSP()
        {
            int stt = 1;
            Console.WriteLine("\n\t=======Danh sach san pham tren he thong========\n\n");
            XmlToList();
            Console.WriteLine("\tSTT  {0}{1}{2}{3}", FixStype("Ma SP", 10), FixStype("Ten SP", 30), FixStype("So Luong", 10), FixStype("Don Gia", 7));            
            foreach (sp objNode in listNode)
            {                
                Console.WriteLine("\t{0}{1}{2}{3}{4}",FixStype(stt.ToString(),5), FixStype(objNode.id, 10), FixStype(objNode.name, 30), FixStype(objNode.soluong, 10), FixStype(objNode.dongia, 7));
                stt++;
            }
            Console.Write("\n\tNhan phim bat ky de ve menu chuong trinh");
            Console.ReadLine();
            Console.Clear();
            start();
        }
        private string FixStype(string name, int max)
        {
            string ret = name;
            for (int i = name.Length; i <= max;i++ )
            {
                ret += " ";
            }
            return ret;

        }
        private void Thoat()
        {
            Environment.Exit(0);
        }
    }
}
